# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     runner.py
    Description:   
 -------------------------------------------------
 """

from core.basecase import BaseCase, ENV
from core import testtools
from core.postman import environment
from core.executor import main

from core.DBClient import db_obj
from core.result_model import TestCaseResult


class TestRunner(object):
    """
    测试运行器
    """

    def __init__(self, case_set, envs):
        self.case_set = case_set
        self.env_data = envs
        self.result = []

    def run(self):
        """
        支持多线程执行
        注意点：如果多个测试类共用某一个全局变量，由于资源竞争可能会出现错误
        :return:
        """
        # 根据数据库的配置初始化数据库的连接
        # db_obj.init_connect(self.env_data.pop('db'))

        # 将测试环境中的数据加载到ENV中
        # ENV.update(self.env_data)  # 更新环境变量
        environment.update(self.env_data.get('Envs'))  # 更新环境变量
        # print(environment)
        # 执行functools.py文件中的代码

        # 遍历所有的测试用例
        for items in self.case_set:
            # 将测试环境中的数据加载到ENV中
            ENV.clear()
            ENV.update(self.env_data)  # 更新环境变量

            # 通过exec将字符串中的python变量加载到functools这个模块的命令空间中
            exec(ENV.get("functools"), testtools.__dict__)

            print("测试套件: , ", items["name"])

            main(items)

            # 创建一个测试结果记录器
            # result = TestCaseResult(total_cases=len(items["cases"]), suite_name=items['name'])
            # 遍历测试集执行里面的用例
            # for item in items["cases"]:
                # 在这里实话化时，ENV已被更新
                # self.perform(item, result)
            # 获取测试执行记录器中的测试结果
            # self.result.append(result.get_result_info())

        # 关闭数据库连接
        # db_obj.close_db_connection()

        return self.result

    # @staticmethod
    # def perform(case, result):
    #     c = BaseCase()
    #
    #     # 执行单条用例
    #     try:
    #         c.perform(case)
    #     except AssertionError as e:
    #         result.add_fail(c, e)
    #         # print("用例执行失败，断言错误（AssertionError）")
    #     except Exception as e:
    #         result.add_error(c, e)
    #         # print("用例执行错误，未知错误", e)
    #     else:
    #         result.add_success(c)
    #         # print("用例执行成功")


if __name__ == '__main__':
    # 测试用例数据
    case = {
        "title": "登陆",
        "interface": {
            "url": "/api/users/login",
            # 如果是项目外的第三方接口，url应该是一个完整的地址：https://www.baidu.com/api/users/register/
            "method": "post"
        },
        "headers": {
            "Content-Type": "application/json"
        },
        "request": {
            "params": {},
            "data": {
                "username": 1234
            },
            "json": {
                "username": "${{username}}",
                "password": "admin123456"
            },
            "files": {}
        },
        "setup_script": open("../tests/setup_script.txt", 'r', encoding='utf-8').read(),
        "teardown_script": open("../tests/teardown_script.txt", 'r', encoding='utf-8').read(),
    }

    case_set = [
        {
            "name": "演示的用例集",
            "cases": [
                case,
                case
            ]
        }
    ]

    # 测试环境
    test_env_data = {
        # 基础地址
        "base_url": "http://127.0.0.1:8000",
        # 默认请求头
        "headers": {
            "Content-Type": "application/json"
        },
        # 环境变量
        "Envs": {
            "username": "test",
        },
        "functools": open("../tests/tools.py", 'r', encoding="utf-8").read(),
        # 数据库配置
        "db": [
            {
                "name": "test",
                "type": "mysql",
                "config": {
                    "host": "127.0.0.1",
                    "port": 3306,
                    "user": "root",
                    "password": "Hell12345..",
                }
            }
        ]
    }

    TestRunner(case_set, test_env_data).run()
